package com.itheima.health.service.impl;

import com.itheima.health.dao.*;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@DubboService
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper menuMapper;


    /**
     * @Author: 位帅帅
     * @Date: 9:16 2021/1/4
     * @Params: [username]
     * @RerurnType: com.itheima.health.pojo.User
     * @Description: 根据用户名查询用户
    */
    @Override
    public User selectByUserName(String username) {
        log.info("[用户登录-参数]username: {}", username);
        User temp = new User();
        temp.setUsername(username);
        User user = userMapper.selectOne(temp);
        Set<Role> roles = new HashSet<>();
        Set<Integer> roleIds = userRoleMapper.findRoleIdsByUserId(user.getId());
        for (Integer roleId : roleIds) {
            Role role = roleMapper.selectByPrimaryKey(roleId);
            Set<Permission> permissions = new HashSet<>();
            Set<Integer> permissionIds = rolePermissionMapper.findPermissionIdsByRoleId(roleId);
            for (Integer permissionId : permissionIds) {
                Permission permission = permissionMapper.selectByPrimaryKey(permissionId);
                permissions.add(permission);
            }
            role.setPermissions(permissions);
            LinkedHashSet<Menu> menus = new LinkedHashSet<>();
            Set<Integer> menuIds = roleMenuMapper.findMenuIdsByRoleId(roleId);
            for (Integer menuId : menuIds) {
                Menu menu = menuMapper.selectByPrimaryKey(menuId);
                menus.add(menu);
            }
            role.setMenus(menus);
            roles.add(role);
        }
        user.setRoles(roles);
        log.info("[用户登录-结果]result: " + user);
        return user;
    }
}
